package cn.yulezhisi.web.controller;

import cn.yulezhisi.common.beans.ResultBean;
import cn.yulezhisi.common.util.Log;
import cn.yulezhisi.entity.SysUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author yulezhisi
 **/

@Api(tags = "登录")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Controller()
public class LoginController{
    
    private final HttpSession session;
    
    private final HttpServletRequest request;
    
    @ApiOperation("登录")
    @RequestMapping(value = "/signin",method = RequestMethod.POST)
    @ResponseBody
    public ResultBean submitLogin(String username, String password, boolean rememberMe, String kaptcha) {
        //获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();
    
        //判断是否登录过
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
            // 所以这一步在调用login(token)方法时,它会走到xxRealm.doGetAuthenticationInfo()方法中,具体验证方式详见此方法
            currentUser.login(token);
            
            //根据需求决定是否 记住我
            token.setRememberMe(rememberMe);
            SysUser user = (SysUser) currentUser.getPrincipal();
            Log.logger.info(user + "");
            session.setAttribute("user", user);
        }
        //登录失败的异常由aop处理
        return new ResultBean<>("success");
    }
    
}

























